package com.papper.mng.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.papper.common.bean.sys.SysModel;
import com.papper.common.bean.sys.SysResource;
import com.papper.common.bean.sys.SysSystem;
import com.papper.common.bean.sys.SysUser;
import com.papper.common.config.PapperStorage;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.service.sys.SysLimitService;
import com.papper.common.service.sys.SysModelService;
import com.papper.common.service.sys.SysResourceService;
import com.papper.common.service.sys.SysSystemService;
import com.papper.common.service.sys.SysUserService;
import com.papper.common.utils.tool.DateTool;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import com.papper.mng.domain.nav.NavBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:Lajiao
 * @Date:2014年8月21日
 * @Time:下午12:42:13
 * @Description:主页面框架
 */
@Controller
public class MainController extends BaseAction {
    @Autowired
    SysUserService     sysUserService;
    @Autowired
    SysResourceService sysResourceService;
    @Autowired
    SysSystemService   sysSystemService;
    @Autowired
    SysLimitService    sysLimitService;
    @Autowired
    SysModelService    sysModelService;

    @GetMapping(value = "/index")
    public String index(Model model) {
        SysUser dbLoginUser = getLoginUser();
        model.addAttribute("sysUser", dbLoginUser);
        // 系统信息
        SysSystem sysSystem = sysSystemService.findSysSystem();
        model.addAttribute("sysSystem", sysSystem);
        model.addAttribute("systemLogo", "");
        // 系统模块
        if (sysSystem != null) {
            List<SysModel> sysModels = sysModelService.findByLimit(sysSystem.getId(), dbLoginUser, DataStatusEnum.OPEN.getCode());
            if (sysModels != null && !sysModels.isEmpty()) {
                List<SysModel> listSort = sysModels.stream().sorted(Comparator.comparing(SysModel::getModelSort)).collect(Collectors.toList());
                model.addAttribute("sysModels", listSort);
            }
        }
        model.addAttribute("stsDay", DateTool.formatDate(new Date(), DateTool.TRADITION_PATTERN));
        return render("system/index");
    }

    @GetMapping(value = "/left")
    public String left(Model model, Long mid) {
        SysUser sysUser = getLoginUser();
        model.addAttribute("mid", mid);
        model.addAttribute("sysUser", sysUser);
        // 超级权限
        if (isSuperUser() && mid == 0) {
            return render("system/left");
        }
        // 过滤菜单
        List<SysResource> sysResources = sysResourceService.findByLimit(mid, sysUser);
        List<SysResource> temp         = Lists.newArrayList();
        if (sysResources != null) {
            for (SysResource sysResource : sysResources) {
                // 保留页面信息
                if (mid.intValue() == sysResource.getModelId().intValue() && sysResource.getResType().intValue() == 0) {
                    temp.add(sysResource);
                }
            }
        }
        model.addAttribute("sysResources", sysResourceService.treeChildList(temp));
        return render("system/left");
    }

    @GetMapping(value = "/nav/list")
    @ResponseBody
    public List<NavBo> navList(Long mid) {
        List<NavBo> navBoList = Lists.newArrayList();
        SysUser     sysUser   = getLoginUser();
        if (isSuperUser() && mid == 0) {
            // 超级管理员
            List<NavBo> childNav = Lists.newArrayList();
            navBoList.add(new NavBo(2, 1, "系统管理", "", "fa fa-windows"));
            navBoList.add(new NavBo(21, 2, "部署系统", "/sys/system", "fa fa-server"));
            navBoList.add(new NavBo(22, 2, "系统模块", "/sys/model", "fa fa-archive"));
            navBoList.add(new NavBo(23, 2, "模块资源", "/sys/resource", "fa fa-folder-open"));

            navBoList.add(new NavBo(3, 1, "用户角色", "", "fa fa-user-circle"));
            navBoList.add(new NavBo(31, 3, "角色管理", "/sys/group", "fa fa-object-ungroup"));
            navBoList.add(new NavBo(32, 3, "用户管理", "/sys/user", "fa fa-users"));

            navBoList.add(new NavBo(4, 1, "系统配置", "", "fa fa-gears"));
            navBoList.add(new NavBo(41, 4, "系统授权", "/sys/auth", "fa fa-pencil-square"));
            navBoList.add(new NavBo(42, 4, "系统字典", "/sys/code", "fa fa-book"));
            navBoList.add(new NavBo(44, 4, "系统配置", "/sys/config", "fa fa-book"));
            navBoList.add(new NavBo(45, 4, "页面配置", "/sys/page/config", "fa fa-check-circle"));
            navBoList.add(new NavBo(46, 4, "请求列表", "/request/mapping", "fa fa-link"));
            return makeTree(navBoList, 1);
        } else {
            List<SysResource> sysResources = sysResourceService.findByLimit(mid, sysUser);
            List<SysResource> temp         = Lists.newArrayList();
            if (sysResources != null) {
                for (SysResource sysResource : sysResources) {
                    if (mid.intValue() == sysResource.getModelId().intValue() && sysResource.getResType().intValue() == 0) {
                        temp.add(sysResource);
                    }
                }
            }
            if (temp != null && !temp.isEmpty()) {
                Collections.sort(temp, Comparator.comparing(SysResource::getSortFamily).thenComparing(SysResource::getResSort));
                temp.forEach(sy -> navBoList.add(new NavBo(sy.getId().intValue(), sy.getUpId(), sy.getResName(), sy.getResUrl(), sy.getResIcon())));
                return makeTree(navBoList, navBoList.get(0).getUpId());
            }
        }
        return navBoList;
    }

    /**
     * @author l'amour solitaire
     * @description 递归菜单
     * @date 2020/3/24 下午3:12
     */
    private static List<NavBo> makeTree(List<NavBo> sysResources, Integer pId) {
        List<NavBo> children  = sysResources.stream().filter(x -> x.getUpId().equals(pId)).collect(Collectors.toList());
        List<NavBo> successor = sysResources.stream().filter(x -> !x.getUpId().equals(pId)).collect(Collectors.toList());
        children.forEach(x -> x.setChildren(makeTree(successor, x.getId())));
        return children;
    }

    @GetMapping(value = "/limit")
    public String limit(Model model) {
        return render("system/limit");
    }

    @GetMapping(value = "/system/setting")
    public String setting(Model model) {
        return render("system/setting");
    }

    @GetMapping(value = "/config/flush")
    @ResponseBody
    public DwzResponse configFlush(HttpServletResponse _response, Model model) throws IOException {
        PapperStorage.initStorage(Lists.newArrayList("Local", "Config", "System"));
        return new DwzResponse("200", "缓存刷新成功！", "closeCurrent");
    }

    @GetMapping(value = "/index/msg")
    @ResponseBody
    public String msg(Model model, HttpServletResponse _response) throws IOException {
        SysUser sysUser = getLoginUser();
        if (sysUser == null) {
            return new JSONObject().toJSONString();
        }
        /**
         * 检索条件
         */
        /**
         * 返回数据
         */
        return new JSONObject().toJSONString();
    }
}
